package com.neuedu.corejava.ch12.homework;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 20190813
 * 
 * 2、编写一个java程序实现文件复制功能，要求将d:/io/copysrc.doc中的内容复制到d:/io/copydes.doc中。 [必做题]
 * 
 * @author admin
 *
 */
public class ch122 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// 创建文件目录
		String pathname = "d:\\io\\copysrc.doc";

		// 创建文件
		String path = "d:\\io";
		File filePath = new File(path);
		boolean bool = filePath.mkdirs();
		if (bool) {
			System.out.println("目录创建成功");
		}

		File file = new File(pathname);
		FileWriter writer=null;
		
		File file2=new File("d:/io/copydes.doc");

		try {
			if (!file.exists()) {
				boolean result = file.createNewFile();
				if(result){
					System.out.println("文件创建成功");
					
					//向文件中输入内容
					writer=new FileWriter(file,true);
					String string="你好呀！java 我想嘤嘤嘤";
					writer.write(string);
					writer.flush();
					
					//拷贝内容
					try(BufferedReader bReader=new BufferedReader(new FileReader(file));
						BufferedWriter bWriter=new BufferedWriter(new FileWriter(file2));
							){
						String content=null;
						while ((content=bReader.readLine())!=null) {
							bWriter.write(content);
							bWriter.newLine();
							System.out.println("拷贝成功！");
						}
					}
							
					
				}else{
					System.out.println("文件创建失败");
				}

			}else{
				boolean ret=file.delete();
				if(ret){
					System.out.println("文件已已经存在，执行文件删除成功！");
				}
				boolean result=file.createNewFile();
				if(result){
					System.err.println("新建文件成功！");
					//向文件中输入内容
					writer=new FileWriter(file,true);
					String string="你好呀！java 我想嘤嘤嘤";
					writer.write(string);
					writer.flush();
					
					
					//拷贝内容
					try(BufferedReader bReader=new BufferedReader(new FileReader(file));
						BufferedWriter bWriter=new BufferedWriter(new FileWriter(file2));
							){
						String content=null;
						while ((content=bReader.readLine())!=null) {
							bWriter.write(content);
							bWriter.newLine();
							System.out.println("拷贝成功！");
						}
					}
					
				}else{
					System.out.println("新建文件失败！");
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(writer!=null)
				try {
						writer.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				};
			}
		}
		

	}


